from django.utils import timezone  # django转换UTC时间为本地时间
from kubernetes import client
from kubernetes.client.rest import ApiException


class OprationIngressApi():
    '''操作ingress'''

    def __init__(self, namespace, ingress_name=None):
        self.namespace = namespace
        self.ingress_name = ingress_name
        from kubernetes import config
        config.load_kube_config(config_file="./kube_conf/local.conf")
        self.coreApi_v1 = client.CoreV1Api()
        self.extensions_v1beta1 = client.ExtensionsV1beta1Api()
        self.networkingV1Api = client.NetworkingV1Api()

    def get_ingress_api(self):

        '''获取ingress列表'''

        try:
            ingress_res = self.extensions_v1beta1.list_namespaced_ingress(namespace=self.namespace,
                                                                          async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': 'ingress 获取失败,%s' % str(e)}
        else:
            results = []
            for ingress in ingress_res.items:
                ingress_data = {}
                ingress_data['name'] = ingress.metadata.name
                ingress_data['host'] = ingress.spec.rules[0].host
                ingress_data['status'] = True
                ingress_data['service_name'] = ingress.spec.rules[0].http.paths[0].backend.service_name
                ingress_data['service_port'] = ingress.spec.rules[0].http.paths[0].backend.service_port
                ingress_data['create_time'] = timezone.localtime(ingress.metadata.creation_timestamp).strftime(
                    "%Y-%m-%d %H:%M:%S")
                results.append(ingress_data)
            return results

    def search_ingress_api(self):
        '''搜索单个ingress'''

        results = []
        for ingress in self.get_ingress_api():
            if self.ingress_name == ingress.get('name'):
                results.append(ingress)
        return results

    def get_ingress_name_api(self):
        '''仅获取namespace对应的所有ingress名称'''

        try:
            ingress_res = self.extensions_v1beta1.list_namespaced_ingress(namespace=self.namespace,
                                                                          async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': 'ingress列表获取失败'}
        else:
            # 此处仅获取metadata.name
            results = [ingress.metadata.name for ingress in ingress_res.items]
            return results

    def delete_ingress_api(self):
        '''删除ingress'''

        try:
            Body = client.V1DeleteOptions()
            ingress_res = self.extensions_v1beta1.delete_namespaced_ingress(namespace=self.namespace,
                                                                            name=self.ingress_name, body=Body,
                                                                            async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': f'ingress {self.ingress_name} 删除失败! {str(e)}'}
        else:
            print(ingress_res.status)
            return {'code': 200, 'msg': 'ingress %s 删除成功!' % self.ingress_name}

    def create_ingress_api(self, service_name, service_port, domain):
        '''创建ingress'''

        metadata_obj = client.V1ObjectMeta(
            name=self.ingress_name,
            namespace=self.namespace
        )
        http_obj = client.ExtensionsV1beta1HTTPIngressRuleValue(paths=[
            client.ExtensionsV1beta1HTTPIngressPath(path="/", backend=client.ExtensionsV1beta1IngressBackend(
                service_name=service_name,
                service_port=int(service_port)))
        ])
        spec_obj = client.ExtensionsV1beta1IngressSpec(
            rules=[
                client.ExtensionsV1beta1IngressRule(host=f'{self.namespace}-{domain}.bblex-inner.com', http=http_obj)]
        )
        Body = client.ExtensionsV1beta1Ingress(
            api_version="extensions/v1beta1",
            kind="Ingress",
            metadata=metadata_obj,
            spec=spec_obj
        )

        try:
            ingress_res = self.extensions_v1beta1.create_namespaced_ingress(namespace=self.namespace,
                                                                            body=Body, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': f'ingress {self.ingress_name} 创建失败,{str(e)}'}
        else:
            print(ingress_res.status)
            return {'code': 200, 'msg': f'ingress {self.ingress_name} 创建成功!'}
